package umaine.ece471.cookbook;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;  
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.message.BasicNameValuePair;  

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class CreateNew extends Activity{
	String prepTime = "30 mins ";
	String cookTime = "30 mins ";
	List<String> data;																//arrayList of strings used for storage
	String dataString = "";															//string used to pass data in the intent
	
	/* PHP script */          
	private static final String SERVER_SCRIPT = "http://mainelyapps.com/mdg/cookbook.php"; 				//location of the database server, and the script used
	
	@Override
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_new);//sets the layout to the custom create_new.xml we created
        this.setTitle("Cookbook-Create New Recipes");
        
        initializeSpinners();  //this was a chunk of code, so we'll put it below
        this.setTitle("Cookbook - Create a Recipe");
         
        
        Button doneButton = (Button) findViewById(R.id.create_button);				//finds the create button on the screen 
        doneButton.setOnClickListener(new View.OnClickListener() {					//creates the action to be done with the create button is clicked
			
			public void onClick(View v) {
				
				data = dataBuilder();												//call the custom dataBuilder function to build data based on the user input
				List<NameValuePair> postParams = new ArrayList<NameValuePair>();	//creates arrayList of NameValuePairs to be used to pass information to database server
				
				postParams.add(new BasicNameValuePair("op","store"));				//lets database know that storage is occurring instead of searching
				postParams.add(new BasicNameValuePair("recipename_creator",data.get(0)));		//adds recipe name and recipe creator to the database(used in a single column)
				//postParams.add(new BasicNameValuePair("Recipe Name",data.get(0)));
				//postParams.add(new BasicNameValuePair("Creator",data.get(1)));
				postParams.add(new BasicNameValuePair("ing1",data.get(1)));			//adds the ingredient1 to the database
				postParams.add(new BasicNameValuePair("in1Unit",data.get(2)));		//adds the ingredient1 unit to the database
				postParams.add(new BasicNameValuePair("ing1Amount",data.get(3)));	//adds the ingredient1 amount to the database
				postParams.add(new BasicNameValuePair("ing2",data.get(4)));			//adds the ingredient2 to the database
				postParams.add(new BasicNameValuePair("ing2Unit",data.get(5)));		//adds the ingredient2 unit to the database
				postParams.add(new BasicNameValuePair("ing2Amount",data.get(6)));	//adds the ingredient2 amount to the database
				postParams.add(new BasicNameValuePair("ing3",data.get(7)));			//adds the ingredient3 to the database
				postParams.add(new BasicNameValuePair("ing3Unit",data.get(8)));		//adds the ingredient3 unit to the database
				postParams.add(new BasicNameValuePair("ing3Amount",data.get(9)));	//adds the ingredient3 amount to the database
				postParams.add(new BasicNameValuePair("ing4",data.get(10)));		//adds the ingredient4 to the database
				postParams.add(new BasicNameValuePair("ing4Unit",data.get(11)));	//adds the ingredient4 unit to the database
				postParams.add(new BasicNameValuePair("ing4Amount",data.get(12)));	//adds the ingredient4 amount to the database
				postParams.add(new BasicNameValuePair("ing5",data.get(13)));		//adds the ingredient5 to the database
				postParams.add(new BasicNameValuePair("ing5Unit",data.get(14)));	//adds the ingredient5 unit to the database
				postParams.add(new BasicNameValuePair("ing5Amount",data.get(15)));	//adds the ingredient5 amount to the database
				postParams.add(new BasicNameValuePair("ing6",data.get(16)));		//adds the ingredient6 to the database
				postParams.add(new BasicNameValuePair("ing6Unit",data.get(17)));	//adds the ingredient6 unit to the database
				postParams.add(new BasicNameValuePair("ing6Amount",data.get(18)));	//adds the ingredient6 amount to the database
				postParams.add(new BasicNameValuePair("ing7",data.get(19)));		//adds the ingredient7 to the database
				postParams.add(new BasicNameValuePair("ing7Unit",data.get(20)));	//adds the ingredient7 unit to the database
				postParams.add(new BasicNameValuePair("ing7Amount",data.get(21)));	//adds the ingredient7 amount to the database
				postParams.add(new BasicNameValuePair("ing8",data.get(22)));		//adds the ingredient8 to the database
				postParams.add(new BasicNameValuePair("ing8Unit",data.get(23)));	//adds the ingredient8 unit to the database
				postParams.add(new BasicNameValuePair("ing8Amount",data.get(24)));	//adds the ingredient8 amount to the database
				postParams.add(new BasicNameValuePair("ing9",data.get(25)));		//adds the ingredient9 to the database
				postParams.add(new BasicNameValuePair("ing9Unit",data.get(26)));	//adds the ingredient9 unit to the database
				postParams.add(new BasicNameValuePair("ing9Amount",data.get(27)));	//adds the ingredient9 amount to the database
				postParams.add(new BasicNameValuePair("instructions", data.get(28)));	//adds recipe instructions to the database
				postParams.add(new BasicNameValuePair("preptime", data.get(29)));	//current database setup handles prep time
				postParams.add(new BasicNameValuePair("cooktime", data.get(30)));	//current database setup handles cook time

				
				try {
					List<String> ret = httpRequest(postParams);						//tries to call httpRequest function with previous parameters
				} catch (Exception e){

				}
		
				
				for(int i =0; i<data.size(); i++){									//creates a single string from all of the data that the user input for the recipe creation
					dataString = dataString+data.get(i)+";";						//single string is used to pass data to an intent, which populate a recipeView class
				}
				try{
					Intent i;														//creates an intent that will create a recipeView based on the user input
					i = new Intent(CreateNew.this, RecipeViewer.class);				//calls recipeViewer.class which is the view for the new recipes
					i.putExtra("dataString",dataString);							//puts the single string, dataString, into the intent
					startActivity(i);												//starts the new activity
				}
				catch(Exception e){
					Toast.makeText(getBaseContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
				}
			}
		});
        
        Button attributeButton = (Button) findViewById(R.id.attributes);			//finds attribute button which allows user to store data for prep and cook time
        attributeButton.setOnClickListener(new View.OnClickListener(){			

			public void onClick(View v) {											//when button is clicked dialog box pops up to screen for user input
				final Dialog dialog = new Dialog(CreateNew.this);
				dialog.setContentView(R.layout.create_new_dialog);
				dialog.setTitle("Enter Attributes");
				
				Button finishButton = (Button) dialog.findViewById(R.id.dialog_finish_button);			//finds finish button
				Button cancelButton = (Button) dialog.findViewById(R.id.dialog_cancel_button);			//finds cancel button
				
				try{
					finishButton.setOnClickListener(new View.OnClickListener() {						//starts activity when finish button is clicked
						public void onClick(View v) {													//stores user button and exits dialog
							EditText prep = (EditText) dialog.findViewById(R.id.dialog_prep_time);			//stores user input for prep time
							EditText cook = (EditText) dialog.findViewById(R.id.dialog_cook_time);			//stores user input for cook time
							prepTime = prep.getText().toString();
							cookTime = cook.getText().toString();
							dialog.dismiss();
							dialog.cancel();
							
						}
					});
					
					cancelButton.setOnClickListener(new View.OnClickListener() {						//starts activity when cancel button is clicked 
						public void onClick(View v) {													//exits dialog
							dialog.dismiss();
							
						}
						
					});
				}catch(Exception e){
					dialog.dismiss();
				}
				dialog.show();
				
			}
			
			
        	
        });
    }
   
	private void initializeSpinners() {									//function that populates the spinners for each of the ingredient units
		Spinner unit1 = (Spinner)findViewById(R.id.units_1);			//spinners uses an array of strings, units_array, that is set up in the values folder
		Spinner unit2 = (Spinner)findViewById(R.id.units_2);
		Spinner unit3 = (Spinner)findViewById(R.id.units_3);
		Spinner unit4 = (Spinner)findViewById(R.id.units_4);
		Spinner unit5 = (Spinner)findViewById(R.id.units_5);
		Spinner unit6 = (Spinner)findViewById(R.id.units_6);
		Spinner unit7 = (Spinner)findViewById(R.id.units_7);
		Spinner unit8 = (Spinner)findViewById(R.id.units_8);
		Spinner unit9 = (Spinner)findViewById(R.id.units_9);
		
		ArrayAdapter adapter = ArrayAdapter.createFromResource(
				this, R.array.units_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		unit1.setAdapter(adapter);
		unit2.setAdapter(adapter);
		unit3.setAdapter(adapter);
		unit4.setAdapter(adapter);
		unit5.setAdapter(adapter);
		unit6.setAdapter(adapter);
		unit7.setAdapter(adapter);
		unit8.setAdapter(adapter);
		unit9.setAdapter(adapter);
		
		
	}

	@Override
	public void finish() {															//called when activity is finished
		super.finish();
	}
	
	List<String> dataBuilder(){														//build our data into a neat item to be passed
		List<String> dataList = new ArrayList<String>();							//to the database
		
		String title;																//stores input recipe title
		String creator;																//stores input recipe creator
		String recipeID;															//stores distinct recipeID that is different for each recipe created
				
		EditText recipeName = (EditText) findViewById(R.id.recipe_name);
		if (recipeName.getText().toString()==null){
			title="";
		}
		else
			title = recipeName.getText().toString();
		
		EditText cookName = (EditText) findViewById(R.id.cook_name);
		if (cookName.getText().toString()==null){
			creator="";
		}
		else
			creator = cookName.getText().toString();
		
		
		recipeID = title+"_"+creator; //recipe id is unique to recipe... ie
																						 //two people can make mac n cheese, but not 
																						 //the same cook.
		dataList.add(recipeID);								//adds the recipeID as the first item in the list
		//dataList.add(recipeName.getText().toString());		//next add the recipe's name
		//dataList.add(cookName.getText().toString());		//next add the cook's name

		EditText size;
		Spinner unit;
		EditText ingredient;
		
		String ingredientAdd;								//Stores string that will be added to database containing each ingredient
		String unitAdd;										//Stores string that will be added to database containing each ingredient unit
		String sizeAdd;										//Stores string that will be added to database containing each ingredient amount
		
		
		for(int i = 1; i<10; i++){							//adds the size, unit, and ingredient for ingredients 1-9 
															//(in that order)
			switch(i){
			case 1:
				size = (EditText) findViewById(R.id.size_1);//checks to see if user input a value; if not blank string is stored (same for all of the cases)
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_1);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_1);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);				//adds ingredient 1 to arrayList
				dataList.add(unitAdd+" ");					//adds ingredient 1 unit to array list
				dataList.add(sizeAdd+" ");					//adds ingredient 1 amount to array list
				break;
				
				
			case 2:
				size = (EditText) findViewById(R.id.size_2);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_2);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_2);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);				//adds ingredient 2 to arraylist
				dataList.add(unitAdd+" ");					//adds ingredient 2 unit to arraylist
				dataList.add(sizeAdd+" ");					//adds ingredient 2 amount to arraylist
				break;
				
				
			case 3:
				size = (EditText) findViewById(R.id.size_3);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_3);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_3);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);				//adds ingredient 3 to arraylist
				dataList.add(unitAdd+" ");					//adds ingredient 3 unit to arraylist
				dataList.add(sizeAdd+" ");					//adds ingredient 3 amount to arraylist
				break;
				
			case 4:
				size = (EditText) findViewById(R.id.size_4);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_4);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_4);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);				//adds ingredient 4 to arraylist 
				dataList.add(unitAdd+" ");					//adds ingredient 4 unit to arraylist
				dataList.add(sizeAdd+" ");					//adds ingredient 4 amount to arraylist
				break;
				
			case 5:
				size = (EditText) findViewById(R.id.size_5);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_5);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_5);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);				//adds ingredient 5 to arraylist
				dataList.add(unitAdd+" ");					//adds ingredient 5 unit to arraylist
				dataList.add(sizeAdd+" ");					//adds ingredient 5 amount to arraylist
				break;
				
			case 6:
				size = (EditText) findViewById(R.id.size_6);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_6);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_6);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);				//adds ingredient 6 to arraylist
				dataList.add(unitAdd+" ");					//adds ingredient 6 unit to arraylist
				dataList.add(sizeAdd+" ");					//adds ingredient 6 amount to arraylist
				break;
				
			case 7:
				size = (EditText) findViewById(R.id.size_7);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_7);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_7);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);					//adds ingredient 7 to arraylist
				dataList.add(unitAdd+" ");						//adds ingredient 7 unit to arraylist
				dataList.add(sizeAdd+" ");						//adds ingredient 7 amount to arraylist
				break;
				
			case 8:
				size = (EditText) findViewById(R.id.size_8);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_8);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_8);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);					//adds ingredient 8 to arraylist
				dataList.add(unitAdd+" ");						//adds ingredient 8 unit to arraylist
				dataList.add(sizeAdd+" ");						//adds ingredient 8 amount to arraylist
				break;
				
			case 9:
				size = (EditText) findViewById(R.id.size_9);//checks to see if user input a value; if not blank string is stored
				if (size.getText().toString()==null)
					sizeAdd="";
				else
					sizeAdd=size.getText().toString();
				
				unit = (Spinner) findViewById(R.id.units_9);
				if (unit.getSelectedItem().toString()==null)
					unitAdd="";
				else
					unitAdd=unit.getSelectedItem().toString();
				
				ingredient = (EditText) findViewById(R.id.item_name_9);
				if (ingredient.getText().toString()==null)
					ingredientAdd="";
				else
					ingredientAdd=ingredient.getText().toString();
				
				dataList.add(ingredientAdd);						//adds ingredient 9 to arraylist
				dataList.add(unitAdd+" ");							//adds ingredient 9 unit to arraylist
				dataList.add(sizeAdd+" ");							//adds ingredient 9 amount to arraylist
				break;
			default:
				break;
			}
		}
		
		EditText instructions = (EditText) findViewById(R.id.instruction_text);	//add the instructions to arraylist from user input
		dataList.add(instructions.getText().toString());			
		
		
		dataList.add(prepTime);
		dataList.add(cookTime);
		String rating = " ";													//creates a null string for rating.  we dont want
		dataList.add(rating);													//the creator to be able to rate their own recipe

		
		return dataList;														//returns the arraylist that was filled throughout this function
		
		
		
		//ok so now the list contains all the information as strings in a list that we want to store in our table.
	}
	
	public static List<String> httpRequest (List<? extends NameValuePair> postParams)					//function that communicates with the database server either for storage or searching
			throws Exception{
		HttpClient client = new DefaultHttpClient();												//creates a http client
		HttpPost request = new HttpPost(SERVER_SCRIPT);												//creates a http request, which is sent to the server(found using php script)
		List<String> ret = new ArrayList<String>();													//creates an array list of strings, which will store the output of the database communication
		
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
						
		request.setEntity(formEntity);																//sets the request to be sent to the server
		HttpResponse response = client.execute(request);											//executes the request
		BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 	//stores output from database request into a bufferedreader
		
		String line = "";
		
		while((line = in.readLine()) != null){														//searches through entire output of the bufferedreader output
			ret.add(line);																			//adds the output one string at a time into the array list of strings ret
		}
		
		in.close();																					//closes the bufferedreader
		return ret; 																				//returns the array list of strings, ret
    }
																			
	
}


